﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;

namespace whu2020302051098
{
    public partial class QueryAttrForm : Form
    {

        //地图数据
        private AxMapControl mMapControl;

        //选中的图层
        private IFeatureLayer mFeatureLayer;

        //根据所选择的图层，查询得到特征类
        private IFeatureClass pFeatureClass = null;

        private List<Control> _buttons = new List<Control>();


        public QueryAttrForm(AxMapControl mapControl)
        {
            InitializeComponent();
            mMapControl = mapControl;

            //绑定事件
            this.Layers.SelectedIndexChanged += cboLayer_SelectedIndexChanged;
            attributes.SelectedIndexChanged += listBoxField_SelectedIndexChanged;

           GetButtons(this);

           //遍历按钮绑定事件
           foreach (var button in _buttons)
           {
               if (button.Text != "Confirm" && button.Text != "Clear")
               {
                   if (button.Text == "space") {

                       button.Click += (sender, args) => { InsertTextAt(sqlWhere, " "); };
                   }
                   else {
                       button.Click += (sender, args) => { InsertTextAt(sqlWhere, button.Text); };
                   }
               }
           }
        }

        public void InsertTextAt(Sunny.UI.UITextBox control, String text)
        {
            string s = control.Text;
            var idx = control.SelectionStart;
            s = s.Insert(idx, text + " ");
            control.Text = s;
            control.Focus();
            control.SelectionStart = idx + text.Length + 1;
        }

        private void GetButtons(Control fatherControl)
        {
            Control.ControlCollection sonControls = fatherControl.Controls;
            foreach (Control control in sonControls)
            {
                if (control is Sunny.UI.UIButton)
                {
                    _buttons.Add(control);
                }
                if (control.Controls != null)
                {
                    GetButtons(control);
                }
            }
        }


        private void QueryAttrForm_Load(object sender, EventArgs e)
        {
            //MapControl中没有图层时返回 
            if (this.mMapControl.LayerCount <= 0)
                return;
            //获取MapControl中的全部图层名称，并加入ComboBox 
            //图层 
            ILayer pLayer;
            //图层名称 
            string strLayerName;

            for (int i = 0; i < this.mMapControl.LayerCount; i++)
            {
                pLayer = this.mMapControl.get_Layer(i);
                strLayerName = pLayer.Name;
                //图层名称加入cboLayer 控件
                this.Layers.Items.Add(strLayerName);
            }

            //默认显示控件的第一个选项 
            this.Layers.SelectedIndex = 0;
        }

        private void cboLayer_SelectedIndexChanged(object sender, EventArgs e)
        {

            this.attributes.Items.Clear();
            //获取cboLayer中选中的图层 
            mFeatureLayer = mMapControl.get_Layer(Layers.SelectedIndex) as IFeatureLayer;
            pFeatureClass = mFeatureLayer.FeatureClass;
            string strFldName;
            for (int i = 0; i < pFeatureClass.Fields.FieldCount; i++)
            {
                strFldName = pFeatureClass.Fields.get_Field(i).Name;
                this.attributes.Items.Add(strFldName); //添加获取的要素类字段名称            } 
                this.attributes.SelectedIndex = 0;
            }

            //修改SQL语句前缀
            sqlPrefix.Text = "select * from " + Layers.SelectedItem + " where";
        }



        private void listBoxField_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sFieldName = attributes.Text;
            values.Items.Clear();
            int iFieldIndex = 0;
            IField pField = null;
            IFeatureCursor pFeatCursor = pFeatureClass.Search(null, true);
            IFeature pFeat = pFeatCursor.NextFeature(); //初始定位
            iFieldIndex = pFeatureClass.FindField(sFieldName); //得到要素类的字段索引
            pField = pFeatureClass.Fields.get_Field(iFieldIndex); //得到图层的字段接口
            while (pFeat != null)
            {
                if (pField.Type == esriFieldType.esriFieldTypeString) //判断字段类型
                {
                    values.Items.Add("'" + pFeat.get_Value(iFieldIndex) + "'"); //这个是为了满足字符串型字段查询的需要
                }
                else
                {
                    values.Items.Add(pFeat.get_Value(iFieldIndex));
                }
                pFeat = pFeatCursor.NextFeature(); //游标下移
            }
        }

        private void Confirm_Click(object sender, EventArgs e)
        {
            try
            {
                mMapControl.Map.ClearSelection(); //清除上次查询结果
                IActiveView pActiveView = mMapControl.Map as IActiveView;
                //pQueryFilter的实例化 
                IQueryFilter pQueryFilter = new QueryFilterClass();
                //设置查询过滤条件时，大家有时需要手工编辑这个字符串，保证语法关系的正确性，否则就需要在得到字段值时需要判断“数据类型”
                pQueryFilter.WhereClause = sqlWhere.Text.Trim(); //需要有规范的格式
                //search的参数第一个为过滤条件，第二个为是否重复执行
                IFeatureCursor pFeatureCursor = mFeatureLayer.Search(pQueryFilter, false);
                //获取查询到的要素 
                IFeature pFeature = pFeatureCursor.NextFeature();
                //判断是否获取到要素 
                while (pFeature != null)
                {
                    mMapControl.Map.SelectFeature(mFeatureLayer, pFeature); //选择要素 
                    pFeature = pFeatureCursor.NextFeature(); //游标下移
                }

                pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);
                pActiveView.Refresh(); //刷新图层
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            this.sqlWhere.Text = "";
            mMapControl.Map.ClearSelection(); //清除查询结果
            IActiveView pActiveView = mMapControl.Map as IActiveView;
            pActiveView.Refresh(); //刷新图层
        }

        private void attributes_DoubleClick(object sender, EventArgs e)
        {
            InsertTextAt(sqlWhere, attributes.SelectedItem.ToString());
        }

        private void values_DoubleClick(object sender, EventArgs e) {
            InsertTextAt(sqlWhere, values.SelectedItem.ToString());
        }

    }
}
